{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 第六章 模块与包\n",
    "\n",
    "* 模块\n",
    "* 包\n",
    "* 内置标准库"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 【提示】Python中的文件、包、模块、库等术语的区别与联系。\n",
    "* 模块：就是.py文件，里面定义了一些函数和变量，需要的时候就可以导入这些模块。 \n",
    "* 包：在模块之上的概念，为了方便管理而将文件进行打包。\n",
    "* 库：具有相关功能模块的集合。这也是Python的一大特色之一，即具有强大的标准库、第三方库以及自定义模块。\n",
    "* 标准库：就是下载安装的python里那些自带的模块，要注意的是，里面有一些模块是看不到的比如像sys模块，这与linux下的cd命令看不到是一样的情况。\n",
    "* 第三方库：就是由其他的第三方机构，发布的具有特定功能的模块。 \n",
    "* 自定义模块：用户自己可以自行编写模块，然后使用。"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1、 模块\n",
    "### 1.1 什么是模块\n",
    "**一个.py文件就称之为一个模块**\n",
    "\n",
    "**Python的内置模块、第三方模块和自定义模块都可称为模块（Modul)\n",
    "\n",
    "1、内置库：\n",
    "Python的基础代码库，覆盖了网络通信、文件处理、数据库接口、图形系统、XML处理等大量内容\n",
    "\n",
    "2、第三方模块：\n",
    "Python 众多使用者的智慧结晶，覆盖了科学计算、Web开发、数据接口、图形系统等众多领域\n",
    "\n",
    "3、自定义模块：\n",
    "用户自定义的代码模块\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.2 模块的优点\n",
    "1、大大提高了代码的可维护性\n",
    "\n",
    "2、编写代码不必从零开始\n",
    "\n",
    "3、避免函数名和变量名冲突\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.3 如何导入模块"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "#【提示】第一种导入方法——import 模块名\n",
    "import numpy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.4142135623730951"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#在导入模块后，通过点符号\".\"连接模块名称和函数名，使用该模块中的函数和属性\n",
    "import numpy\n",
    "numpy.sqrt(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.4142135623730951"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#第二种方法 ：import 模块名 as 别名\n",
    "#当模块的名称很长时，可以指定模块的别名\n",
    "#指定的方式采用\"import 模块名称 as 别名”\n",
    "#在调用时，直接使用别名：\n",
    "import numpy as np\n",
    "np.sqrt(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.4142135623730951"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#第三种方法：from 模块名 import 函数名\n",
    "# 模块包括了大量的函数，只导入需要使用的相应函数，忽略模块的其余内容\n",
    "# 实现方式为“from  模块名称  import  函数名称\"\n",
    "# 用此方法导入的模块中多函数的调用，不需要提供所在模块的名称。\n",
    "from numpy import sqrt\n",
    "sqrt(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [],
   "source": [
    "#【提示】一次导入多个模块：用逗号分隔\n",
    "import pandas as pd, numpy as np, math as math\n",
    "    #【注意】不要写成import pandas,numpy,math as pd,np,ma"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [],
   "source": [
    "#【提示】（4）有层次的文件结构的模块的导入，用句号表示层次关系，例如：\n",
    "\n",
    "import  sklearn.tree.export"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.4 查看内置模块清单"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [],
   "source": [
    "#查看内置模块清单的方法:可用sys模块来查看内置模块的清单\n",
    "import sys\n",
    "\n",
    "# sys.builtin_module_names"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2、包"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.1 什么是包\n",
    "1、按照目录的方式来组织模块，避免了模块名冲突等问题\n",
    "\n",
    "2、一个有层次的文件目录结构，由n个模块或n个子包组成的python应用程序执行环境\n",
    "\n",
    "3、每一个包目录下面都有一个__init__.py文件\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2 如何导入包\n",
    "\n",
    "1、 import 包.子包.模块 \n",
    "\n",
    "\t调用方式：模块名.函数()\n",
    "    \n",
    "2、from 包.子包 import 模块\n",
    "\n",
    "\t调用方式：模块名.函数名()\n",
    "    \n",
    "3、 from 包.子包.模块 import 函数\n",
    "\n",
    "\t调用方式：函数名()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.3 如何查看、下载和更新包"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 查看\n",
    "【提示】可以用pip工具或conda工具，用法：在命令行（Anaconda Prompt）中输入：\n",
    "\n",
    "    # pip list \n",
    "    \n",
    "    # conda list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 下载\n",
    "【提示】可以用pip工具或conda工具，用法：分别在命令行（Anaconda Prompt）命令行中输入\n",
    "\n",
    "    pip install 包名    \n",
    "    conda install 包名"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 更新\n",
    "#【提示】可以用pip工具或conda工具，用法：分别在命令行（Anaconda Prompt）命令行中输入\n",
    "\n",
    "    pip install --upgrade 包名    \n",
    "    conda update 包名"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.4 第三方包\n",
    "由第三方开发人员编写，\n",
    "功能更加丰富，\n",
    "专业方向性更强\n",
    "\n",
    "非自带，需要安装，\n",
    "通过import方法导入\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [],
   "source": [
    "#在数据分析和数据科学项目中，常用的基础包有：\n",
    "    #Pandans：数据加工，一个包含高表现力、数据结构和数据分析工具的库\n",
    "    #Numpy：数组处理，使用 Python 进行科学计算的基础包\n",
    "    #Scikit-learn：机器学习\n",
    "    #Matplotlib：统计可视化，一个 2D 绘图库\n",
    "    #Seaborn：数据可视化\n",
    "    #StatsModels：统计分析\n",
    "    #pandsql:SQL编程\n",
    "    #Django ： 制作 Web 应用程序的特色框架\n",
    "    #requests ： 提供制作 Web 请求的简单方法\n",
    "    #Beautiful Soup ： 用于解析 HTML 并从中提取信息"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.5 如何快速学习包？\n",
    "#【提示】在数据分析和数据科学项目中，可以通过很多方法查看某个包的帮助，建议初学者参考：\n",
    "    #（1）Jupyter Notebook中的help菜单\n",
    "    #（2）查阅特定包的官网，如NumPy的逛网说明文档的URL: https://docs.scipy.org/doc/numpy/reference/?v=20180107143112\n",
    "    #（3）用包提供的内置属性和方法，如查看包的版本号 pd.__version__\n",
    "    #【注意】version的前后各有2个下划线。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0.22.0'"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.__version__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3、内置标准库\n",
    "### 内置标准库简介\n",
    "* 自带的，无需安装\n",
    "* 通过import方法导入\n",
    "\n",
    "常用内置标准库示例  sys、os、json、 random\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.1 sys\n",
    "**sys是Python中较为常用的一个模块，提供了对Python脚本运行时的环境的操作**\n",
    "\n",
    "**sys能够访问与Python解释器联系紧密的函数和变量**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [],
   "source": [
    "# sys.argv #将Python脚本运行时的脚本名以及参数作为一个列表，并输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'win32'"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sys.platform  # 返回当前平台"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [],
   "source": [
    "# sys.path #返回一个列表，该列表为当前脚本的path环境变量"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 os\n",
    "**Python标准库中的一个用于访问操作系统功能的模块**\n",
    "\n",
    "**提供了一种可移植的方法使用操作系统的功能**\n",
    "\n",
    "**提供的接口可以实现跨平台访问**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'D:\\\\Python\\\\Student'"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "os.getcwd()  #查看当前路径"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [],
   "source": [
    "path = 'D:\\\\Python\\\\Student'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1586340910.1971512"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "os.path.getmtime(path)  #文件或文件夹的最后修改时间"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "os.path.exists(path) #文件或文件夹是否存在，返回True 或 False"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.3 json\n",
    "**json.loads() ：函数是将json格式数据转换为字典,可以理解为将字符串形式的json数据转化为字典格式数据**\n",
    "\n",
    "**json.dumps() ：函数是将一个Python数据类型列表进行json格式的编码，可以理解为将字典格式数据转化为字符串形式的json数据**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "json_info的类型：<class 'str'>\n",
      "通过json.dumps()函数处理：\n",
      "dict1的类型：<class 'dict'>\n",
      "{'name': 'data'}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "# json.loads函数的使用，将字符串转化为字典\n",
    "json_info = '{\"name\": \"data\"}'\n",
    "dict1 = json.loads(json_info)\n",
    "print(\"json_info的类型：\"+str(type(json_info)))\n",
    "print(\"通过json.dumps()函数处理：\")\n",
    "print(\"dict1的类型：\"+str(type(dict1)))\n",
    "print(dict1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict1的类型：<class 'dict'>\n",
      "通过json.dumps()函数处理：\n",
      "json_info的类型：<class 'str'>\n",
      "dumps后的数据{\"name\": \"data\"}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "# json.dumps()函数的使用，将字典转化为字符串\n",
    "dict1 = {\"name\": \"data\"}\n",
    "json_info = json.dumps(dict1)\n",
    "print(\"dict1的类型：\"+str(type(dict1)))\n",
    "print(\"通过json.dumps()函数处理：\")\n",
    "print(\"json_info的类型：\"+str(type(json_info)))\n",
    "print('dumps后的数据'+json_info)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "# json.dump()函数的使用，将json信息写进文件\n",
    "json_info = '{\"name\": \"data\"}'\n",
    "file = open('info.json','w',encoding='utf-8')\n",
    "json.dump(json_info,file)\n",
    "file.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"name\": \"data\"}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "#json.load()函数的使用，将读取json信息\n",
    "file = open('info.json','r',encoding='utf-8')\n",
    "info = json.load(file)\n",
    "print(info)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.4 random\n",
    "#### random模块：生成随机数的一个模块"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "11.547114315703574\n",
      "16\n",
      "o\n",
      "is\n",
      "['very', 'is', 'useful', 'Python']\n",
      "[6, 5, 3]\n",
      "[1, 2, 3, 4, 5, 6]\n"
     ]
    }
   ],
   "source": [
    "import random#导入模块\n",
    "a=[1,2,3,4,5,6,]\n",
    "p = [\"Python\", \"is\", \"very\", \"useful\"]\n",
    "print(random.uniform(10, 20))#生成10到20范围内的随机浮点数\n",
    "print(random.randint(10, 20))#生成10到20范围内的随机整数\n",
    "print(random.choice(\"学习Python\"))#从序列中获取一个随机元素\n",
    "print(random.choice(p))#从序列中获取一个随机元素\n",
    "random.shuffle(p)#用于将一个列表中的元素打乱\n",
    "print(p)\n",
    "slice = random.sample(a, 3)  # 从list中随机获取5个元素，作为一个片断返回\n",
    "print(slice)\n",
    "print(a)  # 原有序列并没有改变\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
